package com.ruoyi.framework.filter;


import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Pattern;

// 在请求到达 Tomcat 解析前，通过自定义过滤器拦截包含特殊字符的请求：
@Component
public class InvalidRequestFilter implements Filter {

    // 匹配 HTTP 方法名的合法正则（仅允许 A-Za-z0-9_）
    private static final Pattern VALID_METHOD_PATTERN = Pattern.compile("^[A-Za-z0-9_]+$");

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String method = httpRequest.getMethod();

        if (!VALID_METHOD_PATTERN.matcher(method).matches()) {
            // 拦截非法请求，返回 400 错误
            response.setContentType("text/plain");
            response.getWriter().write("Invalid HTTP method");
            return;
        }
        filterChain.doFilter(request, response);
    }
}
